﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using System.Net;
using WomanMotion.WebApi.Api.Utility;
using WomanMotion.WebApi.Infrastructure.DataBaseCommon;
using WomanMotion.WebApi.Infrastructure.UnifyResult;
using WomanMotion.WebApi.Model.Dtos;
using WomanMotion.WebApi.Model.Dtos.Match;
using WomanMotion.WebApi.Model.Dtos.Team;
using WomanMotion.WebApi.Model.Entitys;
using WomanMotion.WebApi.Service;
using WomanMotion.WebApi.Service.IService;

namespace WomanMotion.WebApi.Api.Controllers
{
    /// <summary>
    /// 比赛管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [XSSFilter]
    [ApiController]
    [DescriptionName("比赛管理", true, 70)]
    public class MatchController : BaseController
    {
        private readonly IMatchService _match;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ISendMessageService _sendMessageService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="match"></param>
        /// <param name="httpContextAccessor"></param>
        public MatchController(ILogger<MatchController> logger, IMatchService match, IHttpContextAccessor httpContextAccessor, ISendMessageService sendMessageService) : base(logger)
        {
            _match = match;
            _httpContextAccessor = httpContextAccessor;
            _sendMessageService = sendMessageService;
        }

        /// <summary>
        /// 创建比赛
        /// </summary>
        /// <param name="dto">DTO</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(SwaggerResultTemplate<MatchVM>), (int)HttpStatusCode.OK)]
        [DescriptionName("创建比赛", true, "比赛管理", "List", "MatchList")]
        public async Task<IResultOutput> Created(CreatedMatchDTO dto)
        {
            var res = await _match.CreatedAsync(dto);
            if (res != null)
            {
                return ResultOutput.Ok(res, "操作成功");
            }
            else
            {
                return ResultOutput.NotOk("操作失败");
            }
        }

        /// <summary>
        /// 启用比赛
        /// </summary>
        /// <param name="ids">主键ID集合</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(SwaggerResultTemplate), (int)HttpStatusCode.OK)]
        [DescriptionName("启用比赛")]
        public async Task<IResultOutput> Enable(PrimaryKeyDTO ids)
        {
            var res = await _match.UpdateDisableAsync(DisableEnum.Enable, ids.Ids);
            if (res > 0)
            {
                return ResultOutput.Ok(new object(), "操作成功");
            }
            else
            {
                return ResultOutput.NotOk("操作失败");
            }
        }

        /// <summary>
        /// 禁用比赛
        /// </summary>
        /// <param name="ids">主键ID集合</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(SwaggerResultTemplate), (int)HttpStatusCode.OK)]
        [DescriptionName("禁用比赛")]
        public async Task<IResultOutput> Disable(PrimaryKeyDTO ids)
        {
            var res = await _match.UpdateDisableAsync(DisableEnum.Disable, ids.Ids);
            if (res > 0)
            {
                return ResultOutput.Ok(new object(), "操作成功");
            }
            else
            {
                return ResultOutput.NotOk("操作失败");
            }
        }

        /// <summary>
        /// 更新比赛
        /// </summary>
        /// <param name="dto">dto</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(SwaggerResultTemplate<MatchVM>), (int)HttpStatusCode.OK)]
        [DescriptionName("更新比赛")]
        public async Task<IResultOutput> Update(UpdateMatchDTO dto)
        {
            var res = await _match.UpdateAsync(dto);
            if (res == null)
            {
                return ResultOutput.NotOk("操作失败");
            }
            return ResultOutput.Ok(res, "操作成功");
        }

        /// <summary>
        /// 更新比赛比分
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(SwaggerResultTemplate<bool>), (int)HttpStatusCode.OK)]
        [DescriptionName("更新比赛比分")]
        public async Task<IResultOutput> UpdateFraction(UpdateMatchFractionDTO dto)
        {
            //获取比赛
            var matchent = await _match.GetEntityAsync(m => m.Id == dto.Id);
            if (matchent == null)
            {
                return ResultOutput.NotOk("查询不到比赛");
            }
            matchent.Teamascore = dto.Teamascore;
            matchent.Teambscore = dto.Teambscore;
            var res = await _match.UpdateEntityAsync(matchent);
            if (res == null)
            {
                return ResultOutput.NotOk("操作失败");
            }
            return ResultOutput.Ok(res, "操作成功");
        }

        /// <summary>
        /// 根据ID获取比赛信息
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(typeof(SwaggerResultTemplate<MatchVM>), (int)HttpStatusCode.OK)]
        [DescriptionName("根据ID获取比赛信息")]
        [AllowAnonymous]
        public async Task<IResultOutput> GetById(long id)
        {
            var res = await _match.GetByIdAsync(id);
            if (res == null)
            {
                return ResultOutput.NotOk("没有数据");
            }
            return ResultOutput.Ok(res, "操作成功");
        }

        /// <summary>
        /// 根据ID获取多表连接比赛信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(typeof(SwaggerResultTemplate<MatchVM>), (int)HttpStatusCode.OK)]
        [DescriptionName("根据ID获取多表连接比赛信息")]
        [AllowAnonymous]
        public async Task<IResultOutput> GetCommonById(long id)
        {
            var res = await _match.GetByIDNavAsync(id);
            if (res == null)
            {
                return ResultOutput.NotOk("没有数据");
            }
            return ResultOutput.Ok(res, "操作成功");
        }

        /// <summary>
        /// 分页获取比赛数据
        /// </summary>
        /// <param name="pars">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(SwaggerResultTemplate<PageViewBase<List<MatchVM>>>), (int)HttpStatusCode.OK)]
        [DescriptionName("分页获取比赛数据")]
        [AllowAnonymous]
        public async Task<IResultOutput> GetPageList(QueryParameterBase pars)
        {
            var res = await _match.GetPageNavListAsync(pars);
            if (res.Data == null || res.Data.Count == 0)
            {
                return ResultOutput.NotOk("没有数据");
            }
            return ResultOutput.Ok(res, "操作成功");
        }

        /// <summary>
        ///前端分页获取比赛数据
        /// </summary>
        /// <param name="pars"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(SwaggerResultTemplate<PageViewBase<List<LeadingMatchVM>>>), (int)HttpStatusCode.OK)]
        [DescriptionName("前端分页获取比赛数据")]
        [AllowAnonymous]
        public async Task<IResultOutput> GetLeadingMatchPageList(QueryParameterBase pars)
        {
            long userid = 0;
            //当HttpContext等于null的时候说明是系统初始化直接取admin的id
            if (_httpContextAccessor.HttpContext.User.Identity.Name != null)
            {
                try
                {
                    userid = long.Parse(_httpContextAccessor.HttpContext.User.Claims.Where(m => m.Type == "UserId").First().Value);
                }
                catch (Exception ex)
                {
                    userid = 0;
                }
            }
            var res = await _match.GetLeadingMatchAsync(pars);
            if (res.Data == null || res.Data.Count == 0)
            {
                return ResultOutput.NotOk("没有数据");
            }
            if (userid == 0)
            {
                return ResultOutput.Ok(res, "操作成功");
            }
            else
            {
                foreach (var item in res.Data)
                {
                    //循环比赛信息
                    foreach (var item2 in item.children)
                    {
                        //比赛ID
                        var isdy = await _sendMessageService.GetAnyAsync(m => m.Matchid == item2.Id && m.Userid == userid);
                        item2.Subscription = isdy;
                    }
                }
                return ResultOutput.Ok(res, "操作成功");
            }
        }

        /// <summary>
        /// 获取距离现在日期最近的赛程信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(typeof(SwaggerResultTemplate<Schedule>), (int)HttpStatusCode.OK)]
        [DescriptionName("获取距离现在日期最近的赛程信息")]
        [AllowAnonymous]
        public async Task<IResultOutput> GetLatelySchedule(long topLevelId, long twoLevelId)
        {
            var res = await _match.GetLatelyScheduleAsync(topLevelId, twoLevelId);
            if (res == null)
            {
                return ResultOutput.NotOk("没有数据");
            }
            return ResultOutput.Ok(res, "操作成功");
        }
    }
}